package com.njlime.core.web;

import com.njlime.core.sdk.wechat.UrlHeader;
import com.njlime.core.utils.PropertiesUtil;
import com.njlime.core.utils.StringUtil;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.service.UnitService;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Map;

/**
 * App前台过滤器
 *
 * @author Dean
 */
public class AppWxInterceptor implements HandlerInterceptor {

    public static final String WX_USER_UNIT_ID = "wx_user_unit_id";
    public static final String WX_USER_ROOT_UNIT_ID = "wx_user_root_unit_id";
    public static final String WX_USER_OPENID = "wx_user_openid";
    public static final String WX_USER_ID = "wx_user_id";
    public static final String WX_USER_NAME = "wx_user_name";
    public static final String WX_USER_PIC = "wx_user_head_url";

    @Resource
    private UnitService unitService;

    //微信端需要登录
    private static final String[] wxNeedLogin = {

    };
    //微信端需要获取openid
    public static final String[] wxNeedOpenid = {
            //支付
            "/app/page/info_pay","/app/page/live_pay","/app/page/mine_pay","/app/member/loginWechat","/app/page/act_pay",
            //活动
            /*"act_lottery","act_sign","act_sign_notice","act_sign_user","act_vote"*/
    };

    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        HttpSession session = request.getSession(true);
        String contextPath = request.getContextPath();
        String fullPath = request.getRequestURI().replace(contextPath, "");
        String queryStr = request.getQueryString();
        if(!StringUtil.isEmpty(queryStr) && queryStr.contains("pv=")){
            fullPath += "/" + StringUtil.getQueryString(queryStr,"pv");
        }
        //判断需要登录的url
        // 从session 里面获取用户名的信息
        Object wxUserId = session.getAttribute(WX_USER_ID);
        // 判断如果没有取到用户信息，就跳转到登陆页面，提示用户进行登陆
        if ((wxUserId == null || "".equals(wxUserId.toString()))) {
            //微信端，需要登录的页面拦截
            for (String item : wxNeedLogin) {
                if (fullPath.equals(item)) {
                    response.sendRedirect(contextPath + "/app/page?pv=login");
                    return false;
                }
            }
        }

        //准备openid
        Integer unit_id = (Integer)request.getSession().getAttribute(AppWxInterceptor.WX_USER_UNIT_ID);
        String baseUrl = "";
        if (request.getServerPort() == 80 || request.getServerPort() == 443) {
            baseUrl = request.getScheme() + "://" + request.getServerName() + request.getContextPath();
        } else {
            baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        }
        for (String item : wxNeedOpenid) {
            if (unit_id != null && fullPath.contains(item)) {
                UnitWxConfig wxConfig = unitService.getWxConfig(unit_id);
                if(wxConfig != null && wxConfig.getWx_type() != null && wxConfig.getWx_type() == UnitWxConfig.WxType.SERVICE){
                    //request.getSession().setAttribute(AppWxInterceptor.WX_USER_OPENID,"oAnDS0rQ5lFN-KVlPhcnM9g8X4tM");
                    Object openid = request.getSession().getAttribute(AppWxInterceptor.WX_USER_OPENID);
                    if (openid != null && !StringUtil.isEmpty(openid.toString())) {
                        return true;
                    } else {
                        try {
                            StringBuilder params = new StringBuilder();
                            for (Map.Entry<String, String[]> param : request.getParameterMap().entrySet()) {
                                params.append(("".equals(params.toString()) ? "" : "&") + param.getKey() + "=");
                                String paramValue = URLEncoder.encode((param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : ""),"utf-8");
                                params.append(paramValue);
                            }
                            String backUri = baseUrl + fullPath;
                            if (!StringUtil.isEmpty(params.toString())) {
                                backUri += "?" + params.toString();
                            }
                            backUri = new String(Base64.encodeBase64(backUri.getBytes("UTF-8")), "UTF-8");
                            String redirect_uri = baseUrl + "/openidServlet?backUrl=" + backUri;
                            boolean weixin = Boolean.valueOf(PropertiesUtil.readValue("/config.properties", "weixin_switch"));
                            if(weixin){
                                System.out.println("跳转微信中转");
                                response.sendRedirect("https://xqn.njlime.com/base/app/wechat/getWxCode?backUri=" + redirect_uri
                                        + "&appid=" + wxConfig.getApp_id() + "&state=" + unit_id);
                            }else{
                                System.out.println("微信直连");
                                response.sendRedirect(UrlHeader.AUTH_URL.replace("APPID", wxConfig.getApp_id())
                                        .replace("REDIRECT", redirect_uri).replace("STATE", unit_id + ""));
                            }
                            return false;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return true;
    }

}
